package com.job.process;

import com.job.utils.MyUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;
import us.codecraft.webmagic.utils.FilePersistentBase;

import java.util.List;
@Component
public class ImagePipeline extends FilePersistentBase implements Pipeline {
    //工具类
    MyUtils myUtils =new MyUtils();
    //文件保存路径
    String savePath;
    //存放链接的key
    public static String urlKey;
    @Value("${pic.filed:picUrl}")
    public void setUrlKey(String urlKey){
        ImagePipeline.urlKey=urlKey;
    }
    /**
     * 需将需要下载的图片url放进PutFiled里面，key为"picUrl"
     */
    public ImagePipeline() {
        setPath("/img/");
    }
    /**
     * 需将需要下载的图片url放进PutFiled里面，key为"picUrl"
     */
    public ImagePipeline(String path) {
        setPath(path);
    }
    @Override
    public void process(ResultItems resultItems, Task task) {
        int length=path.length();
        //保存路径设置为  自定义路径
        if ("\\".equals(path.substring(length-2))||"/".equals(path.substring(length-1))){//添加了斜杠线的
            savePath = this.path;
        }else {//没加斜杠线
            savePath = this.path+ PATH_SEPERATOR;
        }
        //需先将需要下载的图片url放进PutFiled里面，key为"picUrl"
        List<String> picUrl=resultItems.get(urlKey);
        // 当图片链接存在,生成savePath路径的文件夹,然后下载图片
        if(picUrl!=null&&!picUrl.isEmpty()) {//不为空时下载
            checkAndMakeParentDirecotry(savePath);
            myUtils.downloadPic(picUrl,savePath);
            resultItems.put(urlKey,null);//下载完成后将存放的url置空，等待下一次下载
        }
    }
}
